package com.jsh.erp.service;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.jsh.erp.datasource.entities.SysCityCost;
import com.jsh.erp.datasource.mappers.SysCityCostMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CityCostService {

    @Resource
    private SysCityCostMapper cityCostMapper;

    public List<Tree<String>> getCityTree() {
        List<SysCityCost> cities = cityCostMapper.findAllCityCost();

        List<TreeNode<String>> treeNodeList = cities.stream().map(city -> {
            Map<String, Object> extraMap = new HashMap<>();
            extraMap.put("carCost", city.getCarCost());
            extraMap.put("shipCost", city.getShipCost());
            extraMap.put("trainCost", city.getTrainCost());
            // 单个树数据构建
            TreeNode<String> treeNode = new TreeNode<String>()
                    .setId(String.valueOf(city.getId())) // 主键
                    .setParentId(String.valueOf(city.getParentId())) // 父节点ID
                    .setWeight(city.getId())
                    .setName(city.getName()) // 省份名称
                    .setExtra(extraMap); // 扩展字段
            return treeNode;
        }).collect(Collectors.toList());

        // 配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setChildrenKey("children");
        // 最大递归深度
        treeNodeConfig.setDeep(3);

        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(treeNodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    // 给树节点赋值（还能set 父 或子节点树）
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    tree.setWeight(treeNode.getId());
                    // 扩展属性值赋值
                    tree.putExtra("carCost", treeNode.getExtra().getOrDefault("carCost", null));
                    tree.putExtra("shipCost", treeNode.getExtra().getOrDefault("shipCost", null));
                    tree.putExtra("trainCost", treeNode.getExtra().getOrDefault("trainCost", null));
                });
        return treeNodes;
    }
}
